/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gskorupa.univermon.storage;

import com.gskorupa.univermon.config.Configuration;
import com.gskorupa.univermon.versatile.ReportEntity;
import com.gskorupa.univermon.versatile.Report;
import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * @author grzesk
 */
public class InMemory {

    private static volatile InMemory instance = new InMemory();
    HashMap<String, ArrayList> userEntities;

    public static InMemory getInstance() {
        return instance;
    }

    private InMemory() {
        userEntities = new HashMap();
    }

    public Report getReport(Report report) {

        // get from start or from end of list depending on parameters
        // order by is not neede ???
        ArrayList<ReportEntity> list = userEntities.get(report.getUser());
        if (list != null) {
            String maxResults = report.getLimit();
            int max = list.size();
            int size=max;
            report.clear();
            report.setResults(max);
            try {
                max = Integer.parseInt(maxResults);
                if (max > size) {
                    max = size;
                }
            } catch (Exception e) {
            }
            
            // report can't be lager than configured limit
            if(max>Configuration.getInstance().getReportLimit()){
                max=Configuration.getInstance().getReportLimit();
            }
            
            if (report.isFifo()) {
                for (int i = 0; i < max; i++) {
                    report.append(list.get(i));
                }
            } else {
                for (int i = 0; i<max; i++) {
                    report.append(list.get(size-1-i));
                }
            }
        }
        return report;
    }

    public void add(ReportEntity entity) {
        String uid = entity.getUserUID();
        ArrayList list = userEntities.get(uid);
        if (list == null) {
            list = new ArrayList();
        }
        if (list.size() <= 200) {
            list.add(entity);
        }
        userEntities.put(uid, list);
    }

}
